package com.example.learn_mybatis.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.learn_mybatis.pojo.Pager;
import com.example.learn_mybatis.pojo.PermissionParam;
import com.example.learn_mybatis.pojo.RolePermissions;
import com.example.learn_mybatis.mapper.RolePermissionsMapper;
import com.example.learn_mybatis.service.IRolePermissionsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chen
 * @since 2025-07-11
 */
@Service
public class RolePermissionsServiceImpl extends ServiceImpl<RolePermissionsMapper, RolePermissions> implements IRolePermissionsService {

    @Override
    public Pager getRolePermissionById(Integer id, Integer size, Integer page) {
        Pager pager = new Pager();

        Page page1 = new Page(page, size);

        LambdaQueryWrapper<RolePermissions> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(RolePermissions::getRoleId, id);

        Page permissionPage = this.page(page1, queryWrapper);

        pager.setTotal(permissionPage.getPages());
        pager.setList(permissionPage.getRecords());

        return pager;
    }

    @Override
    public boolean batchSavePermissions(PermissionParam permissionParam) {
        Integer roleId = permissionParam.getRoleId();
        ArrayList<RolePermissions> permissions = new ArrayList<>();

        permissionParam.getPermissionIds().forEach(permissionId -> {
            RolePermissions rolePermissions = new RolePermissions();
            rolePermissions.setRoleId(roleId);
            rolePermissions.setPermissionId(permissionId);
            permissions.add(rolePermissions);
        });

        return this.saveBatch(permissions);
    }

    @Override
    public void batchRemovePermission(PermissionParam permissionParam) {
        List<Integer> ids = permissionParam.getIds();
        this.removeBatchByIds(ids);
    }
}
